package org.yejiali.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yejiali.common.constants.SystemConstants;
import org.yejiali.common.enums.AppHttpCodeEnum;
import org.yejiali.common.response.ResponseResult;
import org.yejiali.domain.entity.Comment;
import org.yejiali.domain.vo.CommentVo;
import org.yejiali.domain.vo.PageVo;
import org.yejiali.exception.SystemException;
import org.yejiali.mapper.CommentMapper;
import org.yejiali.mapper.UserMapper;
import org.yejiali.service.CommentService;

import java.util.List;

/**
 * 评论表(Comment)表服务实现类
 *
 * @author yejiali
 * @since 2025-02-20 20:29:00
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 查看文章评论或友链评论
     * @param commentType
     * @param articleId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseResult commentList(String commentType, Long articleId, Integer pageNum, Integer pageSize) {
        //根据文章id查询根评论
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //当查询文章评论时才加上拼接articleId条件
        lambdaQueryWrapper.eq(SystemConstants.ARTICLE_COMMENT.equals(commentType),Comment::getArticleId, articleId)
                .eq(Comment::getRootId, SystemConstants.IS_ROOT_COMMENT);
        //评论类型
        lambdaQueryWrapper.eq(Comment::getType, commentType);
        //分页查询
        Page<Comment> page = new Page<>(pageNum, pageSize);
        page(page, lambdaQueryWrapper);
        // 封装评论，设置评论的昵称
        List<CommentVo> commentVoList = toCommentVoList(page.getRecords());
        //查询所有根评论对应的子评论集合，并且赋值给对应的属性
        for(CommentVo commentVo : commentVoList) {
            commentVo.setChildren(getChildrenComments(commentVo.getId()));
        }
        //响应返回
        return ResponseResult.okResult(new PageVo(commentVoList, page.getTotal()));
    }

    /**
     * 添加评论
     * @param comment
     * @return
     */
    @Override
    public ResponseResult addComment(Comment comment) {
        //评论内容不能为空
        if(!StringUtils.hasText(comment.getContent())) {
            throw new SystemException(AppHttpCodeEnum.CONTEXT_NOT_NULL);
        }
        //MybatisPlus自动填充
        save(comment);
        return ResponseResult.okResult();
    }


    /**
     * 根据根评论id查询子评论的集合
     * @param id
     * @return
     */
    private List<CommentVo> getChildrenComments(Long id) {
                    //查询对应的子评论
                    LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(Comment::getRootId, id);
                    queryWrapper.orderByAsc(Comment::getCreateTime);
                    List<Comment> comments = list(queryWrapper);
        return toCommentVoList(comments);
    }

    private List<CommentVo> toCommentVoList(List<Comment> commentList) {
        List<CommentVo> commentVos = BeanUtil.copyToList(commentList, CommentVo.class);
        //遍历vo集合
        for (CommentVo commentVo : commentVos) {
            //通过creatyBy查询用户的昵称并赋值
            String nickName = userMapper.selectById(commentVo.getCreateBy()).getNickName();
            commentVo.setUsername(nickName);
            //通过toCommentUserId查询用户的昵称并赋值
            //如果toCommentUserId不为-1才进行查询
            if (commentVo.getToCommentUserId() != -1) {
                String toCommentUserName = userMapper.selectById(commentVo.getToCommentUserId()).getNickName();
                commentVo.setToCommentUserName(toCommentUserName);
            }
        }
        return commentVos;

        // 将 commentList 转换为 commentVoList
      /*  List<CommentVo> commentVoList = BeanUtil.copyToList(commentList, CommentVo.class);
        // 收集所有需要查询的用户 ID
        Set<Long> userIds = commentVoList.stream()
                .map(CommentVo::getCreateBy)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        // 一次性查询所有用户信息
        List<User> users = userMapper.selectBatchIds(userIds);
        // 将用户 ID 和昵称映射到一个 Map 中
        Map<Long, String> userIdToUserNameMap = users.stream()
                .collect(Collectors.toMap(User::getId, User::getNickName));
        // 设置昵称
        for (CommentVo commentVo : commentVoList) {
            Long userId = commentVo.getCreateBy();
            if (userId != null) {
                commentVo.setUsername(userIdToUserNameMap.get(userId));
            }
        }
        //收集所有需要的toConmentUserId
        Set<Long> toCommentUserIds = commentVoList.stream()
                .map(CommentVo::getToCommentUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        //查询所有toCommentUserId用到的users
        List<User> toCommentUSer = userMapper.selectBatchIds(toCommentUserIds);
        //将toCommentUserId和昵称映射到一个Map中
        Map<Long, String> toCommentUserIdToUserNameMap = toCommentUSer.stream()
                .collect(Collectors.toMap(User::getId, User::getNickName));
        //设置toCommentUserName
        for (CommentVo commentVo : commentVoList) {
            Long toCommentUserId = commentVo.getToCommentUserId();
            //排除根目录无回复评论人的情况
            if (toCommentUserId!=-1L) {
                commentVo.setToCommentUserName(toCommentUserIdToUserNameMap.get(toCommentUserId));
            }
        }
        return commentVoList;
*/
    }
}





